package com.dragon8869.myspringboot.aspect;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Log4j2
public class LogExecuteTimeAdvice {


    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.dragon8869.myspringboot.annotation.LogExecuteTime)")//切入到@Log标签上
    public void executeTime() {
    }

    @Around("executeTime()")
    public Object around(ProceedingJoinPoint pjp) {
        Class<?> aClass = pjp.getTarget().getClass(); //先获取被织入增强处理的目标对象，再获取目标类的clazz
        String methodName = pjp.getSignature().getName(); //先获取目标方法的签名，再获取目标方法的名
        log.info("className:" + aClass.getName());  // 输出目标方法名
        log.info("methodName: " + methodName);
        Class<?>[] parameterTypes = ((MethodSignature) pjp.getSignature()).getParameterTypes(); //获取目标方法参数类型
        Object[] args = pjp.getArgs();  //获取目标方法的入参
        for (Object arg:args ) {
            log.info("argsName: " + arg); //输出目标方法的参数
        }
        try {
            Method method = aClass.getMethod(methodName, parameterTypes);  //获取目标方法
            log.info("method:" + method);
            log.info("method:" + method.toString());
            log.info("method:" + method.toGenericString());
            long start_time = System.currentTimeMillis();
            Object proceed = pjp.proceed();  //执行目标方法
            long execute_time = System.currentTimeMillis() - start_time;
            log.info("执行时间：" + execute_time + "毫秒");
            log.info("结果: " + proceed);  //打印目标方法的return结果
            return proceed;
        } catch (Throwable th) {
            th.printStackTrace();
            return null;
        }
    }
}
